using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.RoutingSteps.Commands;

/// <summary>
/// 工艺步骤更新命令。
/// </summary>
public sealed record UpdateRoutingStepCommand(long Id, ProcRoutingStepDto RoutingStep) : IRequest<IResult<bool>>;

internal sealed class UpdateRoutingStepCommandHandler(IRepository<ProcRoutingStep> repo) : IRequestHandler<UpdateRoutingStepCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateRoutingStepCommand request, CancellationToken cancellationToken)
    {
        var step = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (step == null)
        {
            return Result.Failure("未找到要更新的工艺步骤");
        }

        step.OperationId = request.RoutingStep.OperationId;
        step.AllowRepeat = request.RoutingStep.AllowRepeat;
        step.IsCritical = request.RoutingStep.IsCritical;
        step.IsMustGood = request.RoutingStep.IsMustGood;
        step.IsCheckMaterial = request.RoutingStep.IsCheckMaterial;
        step.Policies = request.RoutingStep.Policies;
        step.StandardTime = request.RoutingStep.StandardTime;
        step.IsCheckStandard = request.RoutingStep.IsCheckStandard;
        step.Esop = request.RoutingStep.Esop;
        step.StepInstruction = request.RoutingStep.StepInstruction;

        var ok = await repo.UpdateAsync(step, m => new
        {
            m.OperationId,
            m.AllowRepeat,
            m.IsCritical,
            m.IsMustGood,
            m.IsCheckMaterial,
            m.Policies,
            m.StandardTime,
            m.IsCheckStandard,
            m.Esop,
            m.StepInstruction,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
